#include <stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
int count_word(FILE* fp)
{
	int count_word = 0;
	char ch = 0;
	int flag = 0;
	rewind(fp);
	
	ch = getc(fp);
	while (EOF != ch)
	{
		//如果不是空白字符，就是标志单词的开始
		//if ((ch != ' ') && ('!' != ch) && ('*' != ch) && ('\r' != ch) && ('\n' != ch))
		if (isalnum(ch))
		{
			if (flag == 0)
			{
				flag = 1;//标记单词
	}
		}
		//如果是空白字符，再次判断是不是单词状态（排除多个连续空白字符，误被统计成单词）
		else
		{
			if (flag == 1)
			{
				++count_word;
				flag = 0;
			}
		}
		ch = getc(fp);
	}
	//判断最后一个非空白字符的单词
	if (flag == 1)
	{
		++count_word;
	}
	printf("the count of word is：%d\n", count_word);
	return count_word;
}

int count_ch(FILE* fp)
{
	char ch = 0;
	int count_ch = 0;
	rewind(fp);//返回文件开始处
	while (EOF != (ch = getc(fp)))
	{
		++count_ch;
	}
	printf("文本中的字符数为：%d\n", count_ch);
	return count_ch;
}


int main(int argc,char* argv[])
{
	char* file = NULL;
	FILE* fp = NULL;//文件指针，指向file文件
	fp = fopen(argv[2], "rb");//只读
	fseek(fp, 0L, SEEK_END);//定位到文件末尾
	int size = ftell(fp);//从文件开始到末尾的的字节数
 
 
	file = (char*)malloc(size+1);
	memset(file, 0, size+1);
	strcpy(file, argv[2]);
 
	fp = fopen(file, "rb");//只读
	if (fp == NULL)
	{
		fprintf(stderr, "can't open file.txt\n");
		return(EXIT_FAILURE);
	}
	//统计单词数
  if(strcmp(argv[1],"-w")==0)
	count_word(fp);
  else if(strcmp(argv[1],"-c")==0)
  count_ch(fp);
  else 
    printf("cin error\n");
	fclose(fp);
	free(file);
	file = NULL;
	system("pause");
	return(0);
}
